package ch.ethz.fcl.metrobuzz.render.od.flow_view.interactions;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import ch.ethz.fcl.metrobuzz.render.od.flow_view.ODFrame;
import ch.ethz.fcl.metrobuzz.render.od.flow_view.sankey.ODSankeyDiagramData;
import ch.ethz.fcl.metrobuzz.render.od.flow_view.sankey.SankeyNode;
import ch.ethz.fcl.metrobuzz.render.od.flow_view.sankey.SankeyNodeGroup;

public class ODMouseListener extends MouseAdapter {
	private ODFrame frame;
	private ODSankeyDiagramData data;

	public ODMouseListener(ODFrame frame, ODSankeyDiagramData data) {
		this.frame = frame;
		this.data = data;
	}

	@Override
	public void mousePressed(MouseEvent me) {
		if (me.getButton() == MouseEvent.BUTTON3)
			return;

		if (data == null || data.getInitDestinSNList() == null)
			return;

		SankeyNodeGroup clickedGroup = null;

		for (SankeyNodeGroup sng : data.getCurOrginSNList())
			if (sng.getBound().contains(me.getX(), me.getY())) {
				clickedGroup = sng;

				break;
			}

		if (clickedGroup == null)
			for (SankeyNodeGroup sng : data.getCurDestinSNList())
				if (sng.getBound().contains(me.getX(), me.getY())) {
					clickedGroup = sng;
					break;
				}

		if (clickedGroup != null) {
			List<SankeyNode> subNodeList = clickedGroup.getNodeList();
			SankeyNodeGroup parent = clickedGroup.getParentGroup();
			if (subNodeList.size() == 1
					&& !subNodeList.get(0).getId().equals("Others")
					&& parent != null) {
				if (!parent.expanded())
					parent.expand();
				else
					parent.close();
			} else {
				if (!clickedGroup.expanded())
					clickedGroup.expand();
				else
					clickedGroup.close();
			}

			data.expandGroups();
			frame.repaint();
		} 
	}
}
